import roomMgr from './roommgr';

const userList: {[key:string]: SocketIO.Socket} = {};
let userOnline = 0;

export default class Usermgr{
    
    static bind(userId, socket: SocketIO.Socket){
        userList[userId] = socket;
        userOnline++;
    }


    static isOnline(userId){
        let data = userList[userId];
        if(data != null){
            return true;
        }
        return false;
    }

    /**
     * 广播消息
     * @param event 
     * @param data 
     * @param sender 
     * @param includingSender : boolean; true 为跳过sender不给他发消息，其他的都发。
     */
    static broacastInRoom(event: keyof NodeJS.dispatchEventMap, data: seat, sender?, includingSender?){

        const roomId = roomMgr.getUserRoom(sender);
        if(roomId == null){
            return;
        }

        const roomInfo = roomMgr.getRoom(roomId);
        if(roomInfo == null){
            return;
        }

        for(let i = 0; i < roomInfo.seats.length; i++){

            let rs = roomInfo.seats[i];
            if(rs.userId == sender && includingSender != true){
                continue;
            }

            let socket = userList[rs.userId];
            if(socket != null){
                socket.emit(event, data);
            }
        }
    }


    static sendMsg(userId, event: keyof NodeJS.dispatchEventMap, msgdata?){
        const socket = userList[userId];
        if(socket == null){
            return;
        }

        socket.emit(event, msgdata);
    }
}